package com.foxcai.novel.http;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpConnectionManager;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;

/**
 * 
 * 这个例子用来测试报文的发送。 报文发送事例代码，这里使用了MultiThreadedHttpConnectionManager
 * 在发送大量数据时，可以保证资源的回收利用。
 * 
 */
public class EasouHttpCommAction {

	private HttpConnectionManager connectionManager;

	public String send(String reqParams, String reqUrl) {

		HttpClient httpClient = new HttpClient(connectionManager);

		GetMethod method = new GetMethod(reqUrl);
		String resXml = "";
		method.addRequestHeader("Content-Type", "text/xml; charset=utf-8");
		try {
			method.setQueryString(reqParams);

			httpClient.executeMethod(method);

			// 获得返回报文
			resXml = method.getResponseBodyAsString();

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			method.releaseConnection();
		}
		return resXml;
	}

	public EasouHttpCommAction() {
		super();

		// 创建一个线程安全的HTTP连接池
		connectionManager = new MultiThreadedHttpConnectionManager();

		HttpConnectionManagerParams params = new HttpConnectionManagerParams();
		// 连接建立超时
		params.setConnectionTimeout(10000);
		// 数据等待超时
		params.setSoTimeout(30000);
		// 默认每个Host最多10个连接
		params.setDefaultMaxConnectionsPerHost(10);
		// 最大连接数（所有Host加起来）
		params.setMaxTotalConnections(200);

		connectionManager.setParams(params);
	}

}
